<?php
/**
 * ----------------------------------------
 * # 登录操作
 * ----------------------------------------
 * 1. 模拟数据库查询操作
 * 2. 2020年9月14日23:35:16
 * 3. zhang
 * ----------------------------------------
 */
include './common.php';
// 引入 JWT
use \Firebase\JWT\JWT;

$return_data['status'] = 0;
$return_data['info'] = '账号与密码不匹配';

$user_name = $_POST['user_name'] ?? '';
$password = $_POST['password'] ?? '';

if(empty($user_name)){
    $return_data['info'] = '请输入姓名';
    echo json_encode($return_data);
    exit();
}
if(empty($password)) {
    $return_data['info'] = '请输入密码';
    echo json_encode($return_data);
    exit();
}

// 模拟数据库查询操作
$user_info = [];
foreach($users as $k => $v){
    if($user_name == $v['user_name'] && $password == $v['password']){
        $user_info = $v;
        break;
    }
}

if(!empty($user_info)){
    $current_time = time();
    $payload = array(
        'iss' => 'http://jwt.corg', # JWT 签发者
        'aud' => 'http://jwt.com', # 客户端
        'iat' => $current_time, # 签发时间
        'nbf' => $current_time, # 启用时间
        'exp' => $current_time + 3600, # 失效时间
        'user_id' => $user_info['id'], # 额外传值
        'user_name' => $user_info['user_name'], # 额外传值
        'data' => $user_info, # 额外传值
        # 'jti' => '唯一身份标识，主要用来作为一次性token、sub 面向的用户',
    );

    try {
        $return_data['token'] = JWT::encode($payload, $jwt_key);
    } catch (\Throwable $e) {
        $return_data['info'] = isset($jwt_message[$e->getMessage()]) ? $jwt_message[$e->getMessage()] : $jwt_message['default'];
        echo json_encode($return_data);
        exit();
    }
    $return_data['status'] = 1;
    $return_data['info'] = '登录成功';
    $return_data['data'] = array(
        'user_id' => $user_info['id'],
        'user_name' => $user_info['user_name'],
    );
}
echo json_encode($return_data);
